package com.jwdf.uda.ui.fragment.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;

import com.jwdf.uda.R;
import com.jwdf.uda.event.HandleInvalidEvent;
import com.jwdf.uda.runtime.RuntimePermission;
import com.jwdf.uda.utils.BroadcastUtils;
import com.jwdf.uda.utils.ConfigUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.StatisticalUtil;
import com.jwdf.uda.view.LoadingPage;
import com.jwdf.uda.view.ProgressDialog;
import com.jwdf.uda.view.dialog.AlertDialog;
import com.umeng.message.PushAgent;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

public abstract class BaseFragment extends Fragment implements RuntimePermission.PermissionCallbacks {

    private static final String TAG = "ARP";
    private String title;
    private LoadingPage mLoadingPage;
    private boolean mIsLoadingPageShown;
    private boolean mIsRequest = true;
    private ProgressDialog mProgressDlg;
    private List<Call> requestCalls;
    private BroadcastReceiver mLoginInvalidReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(BroadcastUtils.LOGIN_INVALID_ACTION) && !ConfigUtils.isHandledInvalid(context)) {
                showAlertNotice();
                ConfigUtils.setHandledInvalid(context, true);
            }
        }
    };
    public boolean isLoadingPageShowing() {
        return mIsLoadingPageShown;
    }
    public void showLoadingPage() {
        showLoadingPage(View.NO_ID);
    }
    public void showLoadingPage(int layoutId) {
        if(!mIsLoadingPageShown) {
            mIsLoadingPageShown = true;
            if(mLoadingPage == null) {
                mLoadingPage = createLoadingPage();
            }
            mLoadingPage.loading();
            displayLoadingPage(layoutId);
        }
    }
    private boolean displayLoadingPage(int layoutId) {
        ViewGroup layout = null;
        if (getView() != null) {
            int index = -1;
            if (layoutId != View.NO_ID) {
                layout = (ViewGroup) getActivity().findViewById(layoutId);
                if (layout instanceof LinearLayout) {
                    index = 0;
                }
            } else {
                layout = ((ViewGroup) getView());
            }
            if (layout != null && mLoadingPage.getParent() == null) {
                layout.addView(mLoadingPage, index, new LayoutParams(
                        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            }
        }
        return layout != null;
    }
    //    public void showProgressDialogInLocation(int layoutId) {
    //    	showProgressDialog(null, layoutId);
    //    public void showProgressDialogInLocation(int resId,int layoutId) {
    //    	showProgressDialog(getString(resId),layoutId);
    private LoadingPage createLoadingPage() {
        final Context context = getActivity();
        LoadingPage loadingPage = new LoadingPage(context) {
            @Override
            protected void reload() {
                onReload(context);
            }
        };
        return loadingPage;
    }
    protected void onReload(Context context) {
    }
    public void showFailPage(String message) {
        if(mLoadingPage != null) {
            mLoadingPage.failed(message);
        }
    }
    public void showFailPage(int messageId) {
        if(mLoadingPage != null) {
            mLoadingPage.failed(messageId);
        }
    }
    public void showFailPage() {
        if(mLoadingPage != null) {
            mLoadingPage.failed(null);
        }
    }
    protected int getPageLength() {
        return ConfigUtils.getPageLength(getContext());
    }
    public void finishFragment() {
        FragmentActivity activity = getActivity();
        if(activity != null) {
            activity.getSupportFragmentManager().popBackStackImmediate();
        }
    }
    public void finishFragment(String name) {
        FragmentActivity activity = getActivity();
        if(activity != null) {
            activity.getSupportFragmentManager().popBackStackImmediate(name, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public void setLoadFailedMessage(String failedMessage) {
        if(mLoadingPage != null) {
            mLoadingPage.failed(failedMessage);
        }
    }
    public void setLoadFailedMessage(int failedStringId) {
        if(mLoadingPage != null) {
            mLoadingPage.failed(failedStringId);
        }
    }
    public void showProgressDialog() {
        showProgressDialog(null, View.NO_ID);
    }
    public void showProgressDialog(String msg, int layoutId) {
        if(mProgressDlg == null) {
            mProgressDlg = new ProgressDialog(getActivity());
        }
        if(TextUtils.isEmpty(msg)) {
            mProgressDlg.show();
        } else {
            mProgressDlg.show(msg);
        }
        displayView(mProgressDlg, layoutId);
    }
    private boolean displayView(View view, int layoutId) {
        ViewGroup layout = null;
        if(view != null) {
            int index = -1;
            if(layoutId != View.NO_ID) {
                layout = (ViewGroup) getActivity().findViewById(layoutId);
            } else {
                layout = (ViewGroup) getActivity().getWindow().getDecorView();
            }
            if(layout != null) {
                if(layout instanceof LinearLayout) {
                    index = 0;
                }
                layout.addView(view, index, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
            }
        }
        return layout != null;
    }
    public void showProgressDialog(int resId) {
        showProgressDialog(getString(resId), View.NO_ID);
    }
    public boolean progressDialogIsShowing() {
        if(mProgressDlg != null) {
            return mProgressDlg.isShowing();
        }
        return false;
    }
    public void onNewRequestCall(Call call) {
        addRequestCall(call);
    }

    //    }
    private void addRequestCall(Call call) {
        if(requestCalls == null) {
            requestCalls = new ArrayList<>();
        }
        requestCalls.add(call);
    }

    //    }
    protected void startActivityFromFragment(Class<?> targetActivity) {
        startActivityFromFragment(targetActivity, null);
    }
    protected void startActivityFromFragment(Class<?> targetActivity, Bundle argument) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), targetActivity);
        if(argument != null) {
            intent.putExtras(argument);
        }
        getActivity().startActivity(intent);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        RuntimePermission.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BroadcastUtils.registerLoginInvalidBroadcast(getContext(), mLoginInvalidReceiver);
    }
    @Override
    public void onResume() {
        super.onResume();
        if(!TextUtils.isEmpty(getPageName())) {
            StatisticalUtil.onPageStart(getPageName());
        } else {
            StatisticalUtil.onPageStart(getClass().getSimpleName());
        }
    }
    protected String getPageName() {
        return null;
    }
    @Override
    public void onPause() {
        if(!TextUtils.isEmpty(getPageName())) {
            StatisticalUtil.onPageEnd(getPageName());
        } else {
            StatisticalUtil.onPageEnd(getClass().getSimpleName());
        }
        super.onPause();
    }
    @Override
    public void onDestroyView() {
        closeLoadingPage();
        closeProgressDialog();
        cancelRequest();
        super.onDestroyView();
    }
    public void closeLoadingPage() {
        mIsLoadingPageShown = false;
        removeLoadingPage();
    }
    private void removeLoadingPage() {
        if(mLoadingPage != null) {
            ViewGroup parent = (ViewGroup) mLoadingPage.getParent();
            if(parent != null) {
                parent.removeView(mLoadingPage);
            }
        }
    }
    public void closeProgressDialog() {
        if(mProgressDlg != null && mProgressDlg.isShowing()) {
            mProgressDlg.close();
            ViewGroup parent = (ViewGroup) mProgressDlg.getParent();
            if(parent != null) {
                parent.removeView(mProgressDlg);
            }
        }
    }
    public void cancelRequest() {
        if(mIsRequest) {
            if (requestCalls == null)
                return;
            for (int i = 0; i < requestCalls.size(); i++) {
                Call call = requestCalls.get(i);
                if (call == null)
                    return;
                if (!call.isCanceled()) {
                    call.cancel();
                }
            }
            requestCalls.clear();
        }
    }
    @Override
    public void onDestroy() {
        BroadcastUtils.unregisterReceiver(getContext(), mLoginInvalidReceiver);
        super.onDestroy();
    }
    public void setIsRequest(boolean isRequest) {
        this.mIsRequest = isRequest;
    }
    @Override
    public void onPermissionsGranted(int requestCode, List<String> params) {
        Log.d(TAG, "PermissionsGranted");
    }
    @Override
    public void onPermissionsDenied(int requestCode, List<String> params) {
        Log.d(TAG, "PermissionsDenied");
    }
    private void showAlertNotice() {
        final AlertDialog alertDialog = new AlertDialog(getActivity(), getString(R.string.user_login_invalid), new AlertDialog.CallbackListener() {
            @Override
            public void clickYes() {
                handleInvalidLogin();
            }
        });
        alertDialog.setCanDissmiss(false);
        alertDialog.show();
    }
    protected void handleInvalidLogin() {
        ConfigUtils.removeCurrentUser(getContext());
        ConfigUtils.setHttpHeadersCookie(getContext(), "");
        PushAgent.getInstance(getContext()).disable();
        ConfigUtils.setHandledInvalid(getContext(), false);
        EventBusUtil.post(new HandleInvalidEvent());
    }

}
